from flask import Flask, jsonify, request
import requests
import re

app = Flask(__name__)

# Gitee 仓库信息
GITEE_REPO_OWNER = 'Yae_Miko_Fox'
GITEE_REPO_NAME = 'YunJiIP_iteration'
GITEE_API_URL = f'https://gitee.com/api/v5/repos/{GITEE_REPO_OWNER}/{GITEE_REPO_NAME}/releases/latest'
GITEE_ACCESS_TOKEN = 'e490a9bb2f102551be01835919a8ef75'

def get_latest_release():
    headers = {'Authorization': f'token {GITEE_ACCESS_TOKEN}'}
    try:
        response = requests.get(GITEE_API_URL, headers=headers)
        app.logger.info(f"Response status code: {response.status_code}")
        app.logger.info(f"Response content: {response.content}")
        if response.status_code == 200:
            return response.json()
        else:
            app.logger.error(f"Failed to fetch latest release: {response.status_code} - {response.text}")
            return None
    except requests.RequestException as e:
        app.logger.error(f"Request error: {e}")
        return None

def extract_version(tag_name):
    # 使用正则表达式提取版本号
    match = re.search(r'(\d+\.\d+\.\d+)', tag_name)
    if match:
        return match.group(1)
    return None

def compare_versions(v1, v2):
    def normalize(v):
        return [int(x) for x in v.split('.')]
    return normalize(v1) > normalize(v2)

@app.route('/api/check_update', methods=['GET'])
def check_update():
    current_version = request.args.get('version')
    if not current_version:
        return jsonify({'error': 'Version parameter is required'}), 400

    latest_release = get_latest_release()
    if latest_release:
        app.logger.info(f"Latest release: {latest_release}")  # 调试信息
        if 'tag_name' in latest_release and 'assets' in latest_release and latest_release['assets']:
            latest_version = extract_version(latest_release['tag_name'])
            if latest_version:
                if compare_versions(latest_version, current_version):
                    download_url = latest_release['assets'][0]['browser_download_url']
                    return jsonify({
                        'update_available': True,
                        'latest_version': latest_version,
                        'download_url': download_url
                    })
                else:
                    return jsonify({'update_available': False})
            else:
                app.logger.error(f"Failed to extract version from tag_name: {latest_release['tag_name']}")
                return jsonify({'error': 'Failed to extract version from tag_name'}), 500
        else:
            app.logger.error("Invalid release data")
            return jsonify({'error': 'Invalid release data'}), 500
    else:
        app.logger.error("Failed to fetch latest release")
        return jsonify({'error': 'Failed to fetch latest release'}), 500

@app.route('/')
def index():
    return "版本库"

if __name__ == '__main__':
    app.run(debug=True, port=5000)
